import time

from loguru import logger

from config.screen_coordinates import ARCHIVE


class ArchiveProcess:
    def __init__(self, config, state_manager, vision_processor, km_controller):
        self.config = config
        self.state_manager = state_manager
        self.vision = vision_processor
        self.km = km_controller

    def execute(self):
        self.state_manager.wait_until_resumed()
        logger.info("开始执行游戏存档阶段")
        self.escape()


    def escape(self):
        self.km.press_key('F2')
        self.km.move_and_click(*ARCHIVE.escape_npc_coordinate)
        time.sleep(1)
        self.km.move_and_click(*ARCHIVE.escape_confirm_coordinate)
        time.sleep(1)
        self.km.return_to_initial_position()
        clicked_coords = set()
        for _ in range(26):
            x, y, conf = self.vision.find_text("确定", *ARCHIVE.escape_reward_search_area)
            time.sleep(6)
            if x > 0:
                result_list = self.vision.get_ocr_results(*ARCHIVE.escape_reward_list_search_area)
                priorities = ['铜币', '强化石', '石']  # 点击顺序优先级

                for keyword in priorities:
                    for coordinate,text in result_list:
                        if keyword in text and coordinate not in clicked_coords:
                            self.km.move_and_click(*coordinate)
                            clicked_coords.add(coordinate)
                            break  # 每个关键词只点击一个坐标，跳出内层循环
                self.km.move_and_click(x, y, 1)
                break
        self.km.press_key('F2',2)
